package com.example.myapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaParser;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class VideoActivity extends AppCompatActivity {
    private SurfaceView surfaceView;
    private SurfaceHolder holder;
    MediaPlayer player;
    String link;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        link = "https://www.ywicc.edu.cn/__local/A/B3/9D/2D43F0A6B1380BB168E4F57088A_C84A2708_1EC599BA.mp4?e=.mp4";
        surfaceView = findViewById(R.id.surfaceView);
        player = new MediaPlayer();
        try {
            player.setDataSource(this, Uri.parse(link));
            holder = surfaceView.getHolder();
            holder.addCallback(new MyCallback());
            player.prepareAsync();
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    player.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        surfaceView.setOnClickListener(view -> {
            if (player != null && player.isPlaying()) {
                player.pause();
            } else {
                player.start();
            }
        });
    }
    class MyCallback implements SurfaceHolder.Callback{

        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            player.setDisplay(holder);
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            if(player.isPlaying()){
                player.stop();
            }
        }
    }
}